package cn.edu.hrbcu.es.invigilatemanagerment.controller;

import cn.edu.hrbcu.es.invigilatemanagerment.pojo.Role;
import cn.edu.hrbcu.es.invigilatemanagerment.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/Role")
public class RoleController {
    @Autowired
    private IRoleService roleService;

    @RequestMapping("toAddRole")
    public String toAddRole(Model model)
    {
        return "toaddRole";
    }

    @RequestMapping("toUpdateRole")
    public ModelAndView toUpdateRole(Integer id)
    {
        Role role = roleService.queryRoleById(id);
        ModelAndView model = new ModelAndView("toupdateRole");
        model.addObject("role",role);
        return model;
    }

    @RequestMapping("updateRoleById")
    @ResponseBody
    public String updateRoleById(Role role)
    {
        roleService.updateRoleByPrimaryId(role);
        return "OK";
    }
    @RequestMapping("queryAllRole")
    public String queryAllRole(Model model,@RequestParam(value = "pageNow",defaultValue = "1")int pageNow,
                               @RequestParam(value = "pageSize",defaultValue = "5")int pageSize){
        int totalCount = roleService.queryRoleCount();
        int pageCount = (int)Math.ceil((double)totalCount/pageSize);
        List<Map<String,Object>> list = new ArrayList<>();
        List<Role> roles = roleService.queryRolesByPgae(pageNow,pageSize);
        for(Role role:roles)
        {
            Map<String,Object> map = new HashMap<>();
            map.put("id",role.getId());
            map.put("name",role.getName());
            map.put("description",role.getDescription());
            list.add(map);
        }
        model.addAttribute("roles",list);
        model.addAttribute("pageCount",pageCount);
        model.addAttribute("pageNow",pageNow);
        model.addAttribute("pageSize",pageSize);
        return "role";
    }


    @PostMapping(value="insertRole")
    @ResponseBody
    public String insertRole(Role role)
    {
        roleService.insertRole(role);
        return "OK";
    }

    @ResponseBody
    @RequestMapping("queryRoleById")
    public Role queryRoleById(Integer id)
    {
        return roleService.queryRoleById(id);
    }

    @ResponseBody
    @RequestMapping("deleteRoleById")
    public String deleteRoleById(Integer id)
    {
        roleService.deleteRoleByPrimaryId(id);
        return "OK";
    }


}
